/* Copyright (c) 2009 yinquan
   See the file LICENSE.txt for licensing information. */

const Cc = Components.classes;
const Ci = Components.interfaces;

function $(id) {
  return document.getElementById(id);
}

function jsdump(str) {
  Cc['@mozilla.org/consoleservice;1'].getService(Ci.nsIConsoleService).logStringMessage(str);
}

window.addEventListener("load", initialize, false);
window.addEventListener("unload", uninitialize, false);

function emulateClick(ele) {
  jsdump("emulateClick: " + ele.id);
  var doc = $("popup_browser").contentDocument;
  var evt = doc.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, doc.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var result = ele.dispatchEvent(evt);
  jsdump("click result: " + result);
}

function initialize() {
  jsdump("initialize");
  window.sizeToContent();
  var popupBrowser = $("popup_browser");
  popupBrowser.addEventListener("load", pageLoad, true);
  popupBrowser.addEventListener("unload", pageUnload, true);
}

function uninitialize() {
  jsdump("uninitialize");
  var popupBrowser = $("popup_browser");
  popupBrowser.removeEventListener("load", pageLoad, false);
  popupBrowser.removeEventListener("unload", pageUnload, true);
}

function autoSubmiForm() {
  var doc = $("popup_browser").contentDocument;
  var form = doc.forms[0];
  jsdump("form: " + form);
  var btnConfirm = doc.getElementById("btn_confirm");
  var btnCancel = doc.getElementById("btn_cancel");
  if (btnConfirm != null && btnCancel != null && doc.title == "确认") {
    jsdump("澳门网提交表单：btn_confirm: " + btnConfirm + ";btn_cancel:" + btnCancel);
    emulateClick(btnConfirm);
  }
}

function pageLoad(event) {
  //alert("pageLoad");
  if (event.originalTarget.nodeName == "#document") {
    var doc = event.target;
    //设置窗口标题
    var winDoc = window.document;;
    var win = winDoc.getElementById("popup_window");
    var title = win.getAttribute("title");
    title = doc.title + " - " + title;
    jsdump("window.title: " + title);
    win.setAttribute("title", title);

    //如果有表单，并且是有指定的ID就自动点击，提交表单
    if (doc.forms != undefined && doc.forms.length == 1) {
      jsdump("timer.initWithCallback: autoSubmiForm();");
      var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
      timer.initWithCallback(autoSubmiForm, 1000, Ci.nsITimer.TYPE_ONE_SHOT);
      //window.setTimeout("autoSubmiForm();", 1000);
    }
  }
}

function pageUnload() {
  jsdump("pageUnload...");

}